package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.BoreholeConditionInputDto;
import com.b511.swpu.cementbackend.service.BurstPressureService;
import com.b511.swpu.cementbackend.entity.BurstPressure;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.BurstPressureRepository;
import com.b511.swpu.cementbackend.util.*;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.JoinType;
import java.util.Optional;

@Service
public class BurstPressureServiceImpl implements BurstPressureService {
    private final BurstPressureRepository burstPressureRepository;

    public BurstPressureServiceImpl(BurstPressureRepository burstPressureRepository) {
        this.burstPressureRepository = burstPressureRepository;
    }

    @Override
    public R getBurstPressureByCondition(BoreholeConditionInputDto boreholeConditionInputDto, PageRequest pageRequest){
        return R.ok().putData(burstPressureRepository.findAll((Specification<BurstPressure>) (root, cq, cb)
                -> Help.createPredicate(boreholeConditionInputDto, root.join("borehole", JoinType.LEFT), cb), pageRequest));
    }

    @Override
    @Transactional
    public R updateBurstPressure(Long id, BurstPressure updateBurstPressure){
        Optional<BurstPressure> optionalBurstPressure = burstPressureRepository.findById(id);
        if(!optionalBurstPressure.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        BurstPressure burstPressure = optionalBurstPressure.get();
        CopyUtil.copyProperties(updateBurstPressure,burstPressure);
        burstPressureRepository.save(burstPressure);
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteBurstPressure(Long id){
        burstPressureRepository.deleteById(id);
        return R.ok();
    }

}
